#include "ProjectileManager.h"
#include <Ogre.h>

template<> ProjectileManager* Ogre::Singleton<ProjectileManager>::ms_Singleton = 0;

ProjectileManager* ProjectileManager::getSingletonPtr(void)
{
    return ms_Singleton;
}
ProjectileManager& ProjectileManager::getSingleton(void)
{  
    assert( ms_Singleton );  return ( *ms_Singleton );  
}

ProjectileManager::ProjectileManager(Ogre::SceneManager* sceneManager)
{
	sceneMgr = sceneManager;
	m_CurrentProjectile = 0;
	m_MaxProjectiles = 100;


	for(int i = 0; i < m_MaxProjectiles; i++)
	{
		this->addBaseProjectile();
	}

	m_CurrentMissile = 0;
	m_MaxMissiles = 100;


	for(int i = 0; i < m_MaxMissiles; i++)
	{
		this->addBaseMissile();
	}

}

ProjectileManager::~ProjectileManager(void)
{
}

void ProjectileManager::addBaseProjectile()
{
	BaseProjectile* bProj = new BaseProjectile("", sceneMgr);
	m_BaseProjectiles.push_back(bProj);
}

void ProjectileManager::addBaseProjectileFromCache(Ogre::Vector3 pPos, Quaternion pOrientation)
{
	BaseProjectile* bProj = m_BaseProjectiles[m_CurrentProjectile];
	bProj->resetProjectile(pPos, pOrientation);
	
	m_CurrentProjectile++;

	if(m_CurrentProjectile >= m_MaxProjectiles)
		m_CurrentProjectile = 0;
}

void ProjectileManager::updateProjectiles(double timeSinceLastFrame)
{

	size_t size = m_BaseProjectiles.size();

	//BaseProjectile* bProj;
	for(int i = 0; i < size; ++i)
	{
		if(m_BaseProjectiles[i]->getActiveState() == true){
			m_BaseProjectiles[i]->updateProjectile(timeSinceLastFrame);

			if (m_BaseProjectiles[i]->aliveTimer->getMilliseconds() > m_BaseProjectiles[i]->aliveTimerMax){
				m_BaseProjectiles[i]->setActiveState(false);
			}
		}
	}
}

void ProjectileManager::addBaseMissile()
{
	BaseMissile* bMissile = new BaseMissile(sceneMgr);
	m_BaseMissiles.push_back(bMissile);
}

void ProjectileManager::addBaseMissileFromCache(Ogre::Vector3 pPos, Quaternion pOrientation, Vector3 target)
{
	BaseMissile* bMissile = m_BaseMissiles[m_CurrentMissile];
	bMissile->resetMissile(pPos, pOrientation, target);
	
	m_CurrentMissile++;

	if(m_CurrentMissile >= m_MaxMissiles)
		m_CurrentMissile = 0;
}

void ProjectileManager::updateMissiles(double timeSinceLastFrame)
{

	size_t size = m_BaseMissiles.size();

	//BaseMissile* bMissile;
	for(int i = 0; i < size; ++i)
	{
		if(m_BaseMissiles[i]->getActiveState() == true){
			m_BaseMissiles[i]->updateMissile(timeSinceLastFrame);

			if (m_BaseMissiles[i]->aliveTimer->getMilliseconds() > m_BaseMissiles[i]->aliveTimerMax){
				m_BaseMissiles[i]->setActiveState(false);
			}
		}
	}
}
